import {Injectable, UnauthorizedException} from '@nestjs/common';
import {PassportStrategy} from '@nestjs/passport';
import { Strategy } from 'passport-local';
import {AuthService} from './auth.service';



@Injectable()
export class HttpStrategy extends PassportStrategy(new Strategy({
    usernameField: 'username',
    passwordField: 'password'
  })) {

    constructor(private readonly authService: AuthService) {
        super();
    }

    async validate(username: string, password: string, done: Function) {
        const authObject: {username: string, password: string} = { username, password };
        // const decoded = Buffer.from(token, 'base64').toString();
        // console.log(decoded);
        try {
            // authObject = JSON.parse(decoded);
            // console.log(authObject);
            const user = await this.authService.validateUser(authObject);
            if (!user) {
                return done(new UnauthorizedException(), false);
            }
            done(null, user);
        } catch (e) {
            return done(new UnauthorizedException(), false);
        }
    }
}
